<template>
  <div class="uploadWrapper">
    <div class="imglength"
      v-if="imgLists.length>0">{{msg}}已上传{{imgLists.length}}个文件,文件后缀{{imgLists[0].substring(imgLists[0].lastIndexOf(".")+1)}},点击<a style="color:black;font-weight: bold;" :href="imgLists[0]" target="_blank">查看</a>。</div>
    <div class="imglength"
      v-else-if="isShowMsg">{{msg}}已上传{{imgLists.length}}个文件。</div>

    <vuedraggable class="vue-draggable"
      :class="{ single: isSingle, maxHidden: isMaxHidden }"
      v-model="imgLists"
      tag="ul"
      draggable=".draggable-item"
      @start="onDragStart"
      @end="onDragEnd">
      <!-- 拖拽元素 -->
      <li v-for="(item, index) in imgLists"
        :key="item + index"
        class="draggable-item"
        :style="{ width: width + 'px', height: height + 'px' }">
         <img src="../../assets/filetype/dat.png" class="imgs"/>
        <div class="shadow"
          @click="onRemoveHandler(index)">
          <i class="el-icon-delete"></i>
        </div>
      </li>
      <!-- 上传按钮 -->
      <!-- :headers="headers" -->
      <el-upload v-if="imgLists.length<limit"
        slot="footer"
        ref="uploadRef"
        class="uploadBox"
        :style="{ width: width + 'px', height: height + 'px' }"
        :data="uploadData"
        :action="uploadImgUrl"
        accept=".*"
        :show-file-list="false"
        :multiple="true"
        :limit="limit"
        :before-upload="beforeUpload"
        :on-success="onSuccessUpload"
        :on-exceed="onExceed">
        <i class="uploadIcon el-icon-picture-outline">
          <template v-if="isShowUploadText">
            <span class="uploading"
              v-show="isUploading">正在上传...</span>
            <span v-if="!isUploading && limit && limit !== 99 && !isSingle"
              class="limitTxt">上传文件</span>
          </template>
        </i>
      </el-upload>
    </vuedraggable>
    <el-dialog title="查看文件"
      :visible.sync="dialogVisible">
      <img :width="width"
        :height="height"
        :src="dialogImageUrl"
        alt="" />
    </el-dialog>
  </div>
</template>

<script>
import vuedraggable from "vuedraggable";
import tools from "@/utils/tools";
import { getAllUploadToken } from "@/api/monitor/file";
export default {
  name: "ImgUpload",
  components: { vuedraggable },
  props: {
    // 图片数据(图片url组成的数组) 通过v-model传递
    value: {
      type: Array,
      default () {
        return [];
      },
    },
    // 限制上传的图片数量+
    limit: {
      type: Number,
      default: 1,
    },
    msg: {
      type: String,
      default: "",
    },
    // 限制上传图片的文件大小(kb)
    size: {
      type: Number,
      default: 200 * 1024 * 1024,
    },
    // 是否是单图上传(单图上传就是已传图片和上传按钮重叠)
    isSingle: {
      type: Boolean,
      default: false,
    },
    // 图片显示的宽度(px)
    width: {
      type: Number,
      default: 100,
    },
    // 图片显示的高度(px)
    height: {
      type: Number,
      default: 100,
    },
    //默认图片url
    imageStr: {
      type: String,
      default: "",
    },
    isShowMsg: {
      type: Boolean,
      default: true,
    },
    isShowUploadText: {
      type: Boolean,
      default: true,
    }
  },

  data () {
    return {
      isUploading: false, // 正在上传状态
      isFirstMount: true, // 控制防止重复回显
      dialogVisible: false,
      dialogImageUrl: "",
      uploadImgUrl: "https://upload-z2.qiniup.com",
      upload_domain: "",
      uploadData: { token: "", key: "" },
      itemUrl: "",
      imgLists: [],
      imgNumber: 0,
      zIndex: 3000,
      quantity: 0,
    };
  },

  computed: {
    // 图片数组数据
    imgList: {
      get () {
        return this.value;
      },
      set (val) {
        if (val.length < this.imgList.length) {
          // 判断是删除图片时同步el-upload数据
          this.syncElUpload(val);
        }
        // 同步v-model
        this.$emit("input", val);
      },
    },
    // 控制达到最大限制时隐藏上传按钮
    isMaxHidden () {
      return this.imgList.length >= this.limit;
    },
  },

  watch: {
    value: {
      handler (val) {
        if (this.value) {
          if (this.isFirstMount && this.value.length > 0) {
            this.syncElUpload();
          }
        }

      },
      deep: true,
    },
  },
  created () {
    this.imgData();
  },
  mounted () {
    if (this.value != null) {
      if (this.value.length > 0) {
        this.syncElUpload();
      }

    }

  },

  methods: {
    imgData () {
      if (!this.imageStr) {
        this.imgLists = [];
      } else {
        let img = this.imageStr.split(",").map((item, index) => {
          return item;
        });
        this.imgLists = img;

      }
    },
    // 同步el-upload数据
    syncElUpload (val) {
      const imgList = val || this.imgList;
      this.imgLists.push({ url: imgList });
      this.$refs.uploadRef.uploadFiles = imgList.map((v, i) => {
        return {
          name: "pic" + i,
          url: v,
          status: "success",
          uid: tools.createUniqueString(),
        };
      });
      this.isFirstMount = false;
    },
    // 上传图片之前
    beforeUpload (file) {
      if (this.size < file.size) {
        this.$message.error("上传文件大小不符合要求!");
        return false;
      }
      let fileName = {fileName:file.name};
      let _self = this;
      return new Promise((resolve, reject) => {
        getAllUploadToken(fileName)
          .then((response) => {
            _self.uploadData.key = response.data.key;
            _self.uploadData.token = response.data.token;
            _self.upload_domain = response.data.domain;
            resolve(true);
          })
          .catch((err) => {
            console.log("出错了...", err);
            reject(false);
          });
      });
    },
    selectImg () {
      let itemUrl = "";
      for (let i = 0; i < this.imgLists.length; i++) {
        itemUrl += this.imgLists[i];
        if (i != this.imgLists.length - 1) {
          itemUrl += ','
        }
      }
      console.log(itemUrl, 'itemUrl');
      this.$emit("update:imageStr", itemUrl.toString());

    },
    selectImgs () {
      let itemUrl = "";
      for (let i = 0; i < this.imgLists.length; i++) {
        itemUrl += this.imgLists[i];
        if (i != this.imgLists.length - 1) {
          itemUrl += ','
        }
      }
      console.log(itemUrl, 'itemUrl');
      this.$emit("update:imageStr", itemUrl.toString());

    },
    selectImgBanner () {
      let itemUrl = "";
      for (let i = 0; i < this.imgLists.length; i++) {
        itemUrl += this.imgLists[i];
        if (i != this.imgLists.length - 1) {
          itemUrl += ','
        }
      }
      console.log(itemUrl, 'itemUrl');
      this.$emit("update:imageStr", itemUrl.toString());

    },
    selectImgShare () {
      let itemUrl = "";
      for (let i = 0; i < this.imgLists.length; i++) {
        itemUrl += this.imgLists[i];
        if (i != this.imgLists.length - 1) {
          itemUrl += ','
        }
      }
      console.log(itemUrl, 'itemUrl');
      this.$emit("update:imageStr", itemUrl.toString());

    },
    // 上传完图片
    onSuccessUpload (res, file, fileList) {
      // 这里需要根据你自己的接口返回数据格式和层级来自行修改
      if (res.key) {
        // 判断接口上传成功
        let itemUrl = "";
        if (this.imgLists) {
          if (this.imgLists.length < this.limit) {
            let urls = this.upload_domain + res.key;
            // 未超限时，把接口返回的图片url地址添加到imgList
            this.imgLists.push(urls);
            for (let i = 0; i < this.imgLists.length; i++) {
              itemUrl += this.imgLists[i];
              if (i != this.imgLists.length - 1) {
                itemUrl += ','
              }
            }
            this.$emit("update:imageStr", itemUrl.toString());
          }

        } else {
          itemUrl = this.upload_domain + res.key; +',';
          this.$emit("update:imageStr", itemUrl.toString());
        }

      } else {
        // 判断接口上传失败
        this.syncElUpload();
        this.$message({ type: "error", message: "上传失败" });
      }
      this.isUploading = false;
    },
    // 移除单张图片
    onRemoveHandler (index) {
      this.$confirm("确定删除该文件?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.imgLists.splice(index, 1);
          let itemUrl = "";
          for (let i = 0; i < this.imgLists.length; i++) {
            itemUrl += this.imgLists[i];
            if (i != this.imgLists.length - 1) {
              itemUrl += ','
            }
          }
          this.$emit("update:imageStr", itemUrl.toString());
        })
        .catch(() => { });
    },
    drag (index) {
      let itemUrl = "";
      for (let i = 0; i < this.imgLists.length; i++) {
        itemUrl += this.imgLists[i];
        if (i != this.imgLists.length - 1) {
          itemUrl += ','
        }
      }

      this.$emit("update:imageStr", itemUrl.toString());
    },
    // 超限
    onExceed () {
      this.$refs.uploadRef.abort(); // 取消剩余接口请求
      this.syncElUpload();
      this.$message({
        type: "warning",
        message: `文件超限，最多可上传${this.limit}个文件`,
      });
    },
    onDragStart (e) {
      e.target.classList.add("hideShadow");
    },
    onDragEnd (e) {
      e.target.classList.remove("hideShadow");
      this.drag()
    },
  },
};
</script>

<style lang="less" scoped>
/deep/ .el-upload {
  width: 100%;
  height: 100%;
}

// 上传按钮
.uploadIcon {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed #c0ccda;
  background-color: #fbfdff;
  border-radius: 6px;
  font-size: 20px;
  color: #999;

  .limitTxt,
  .uploading {
    position: absolute;
    bottom: 10%;
    left: 0;
    width: 100%;
    font-size: 13px;
    text-align: center;
  }
}
.imglength {
  color: #999;
  font-size: 13px;
  position: relative;
}
// 拖拽
.vue-draggable {
  display: flex;
  flex-wrap: wrap;

  .draggable-item {
    margin-right: 5px;
    margin-bottom: 5px;
    border: 1px solid #ddd;
    border-radius: 6px;
    position: relative;
    overflow: hidden;

    .el-image {
      width: 100%;
      height: 100%;
    }

    .shadow {
      position: absolute;
      top: 0;
      right: 0;
      background-color: rgba(0, 0, 0, 0.5);
      opacity: 0;
      transition: opacity 0.3s;
      color: #fff;
      font-size: 18px;
      line-height: 18px;
      padding: 2px;
      cursor: pointer;
      border-radius: 5px;
    }
    &:hover {
      .shadow {
        opacity: 1;
      }
    }
  }
  &.hideShadow {
    .shadow {
      display: none;
    }
  }
  &.single {
    overflow: hidden;
    position: relative;

    .draggable-item {
      position: absolute;
      left: 0;
      top: 0;
      z-index: 1;
    }
  }
  &.maxHidden {
    .uploadBox {
      display: none;
    }
  }
}
// el-image
.el-image-viewer__wrapper {
  .el-image-viewer__mask {
    opacity: 0.8;
  }
  .el-icon-circle-close {
    color: #fff;
  }
}
</style>
